package org.example.config;

import org.example.filter.JwtAuthenticationTokenFilter;
import org.example.handler.MyAccessDeniedHandler;
import org.example.handler.MyLoginFailureHandler;
import org.example.handler.MyLoginSuccessHandler;
import org.example.handler.MyLogoutSuccessHandler;
import org.example.service.security.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.NoOp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * @author beikbei
 * @version 1.0
 * @description: TODO
 * @date 2024/5/11 9:56
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.formLogin()
////                .loginPage() // 自定义登陆界面
////                .usernameParameter("username") // 表单中的用户名项
////                .passwordParameter("password") // 表单中的密码项
////                .loginProcessingUrl("/login") // 登录路径，表单向该路径提交，提交后自动执行 UserDetailsService的方法
////                .successForwardUrl("/main") // 登录成功后跳转的路径
//                .successHandler(new MyLoginSuccessHandler()) // 登录成功处理器
//                .failureHandler(new MyLoginFailureHandler()); // 配置登录失败处理器
////                .failureForwardUrl("/fail"); // 登录失败后跳转的路径
//        http.csrf().disable();
//
//        http.logout()
//                .logoutUrl("/logout")
////                        .logoutSuccessUrl("/login.html") // 退出登陆后跳转的路径
//                .clearAuthentication(true) // 清楚认证状态，默认为true
//                .invalidateHttpSession(true) // 销毁HttpSession对象，默认为true
//                .logoutSuccessHandler(new MyLogoutSuccessHandler());
//
//        // 配置需要认证的资源
//        http.authorizeRequests()
//                .antMatchers("/login.html").permitAll() // 登录页面不需要认证
//                .antMatchers("/fail").permitAll() // 失败页不需要认证
//                .antMatchers("/noPermission.html").permitAll()
//                .antMatchers("/main.html").authenticated()
////                .antMatchers("/reportform/find").hasAnyAuthority("/reportform/find")
////                .antMatchers("/salary/find").hasAnyAuthority("/salary/find")
////                .antMatchers("/staff/find").hasAnyAuthority("/staff/find")
////                .anyRequest().authenticated();// 其余所有请求都需要认证
//                .anyRequest().access("@myAuthorizationService.hasPermission(request, authentication)");
//
//        http.rememberMe()
//                .userDetailsService(userDetailsService()) // 登录逻辑交给哪个对象
//                .tokenRepository(persistentTokenRepository) // 持久层对象
//                .tokenValiditySeconds(30); // 保持时间，单位：秒
//
//        http.exceptionHandling()
//                .accessDeniedHandler(new MyAccessDeniedHandler());

        // 实现了自定义的登录逻辑
        http.userDetailsService(userDetailsService);



        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //这个相当于返回了一个http
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
//                .antMatchers("/testCors").hasAuthority("system:dept:list222")
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        //添加过滤器
        //这里的意思是，在处理登录之前，检验JWT
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //配置异常处理器
        http.exceptionHandling()
                //配置认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        //允许跨域
        http.cors();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
